"use strict";
import $crypto from 'crypto-js'
import md5 from 'js-md5';
let Base64 = require('js-base64').Base64;
import $glob from '../../../globalConfig';

// 加密
function Encode(str) {
  return Base64.encode(str);
}

//解密
function Decode(str) {
  return Base64.decode(str);
}

//md5 加密
function MD5(msg) {
  return md5(msg).toString();
}

/**
 * 消息加密发送
 * @param Object|null data 要发送的数据对象
 * @return String 完整加密体
 */
function encrypt(data) {
  if (!data) data = {};
  if ($glob.HTTP_CRYPTO) console.info('发送数据', data);
  let ts = Math.floor(new Date().getTime() / 1000);
  let body = {
    "time": ts,
    "isTime": 0,
    "code": "200",
    "data": data
  };
  return {
    'body': encryptAes(JSON.stringify(body))
  };
}


/**
 * 消息解密
 * @param Object body
 * @return Object 解密后的真实内容
 */
function decrypt(body) {

  if (!body) {
    if (!$glob.HTTP_CRYPTO) console.warn('解密体空的', body);
    return {};
  }

  let json = decryptAes(body)
  if (!json) {
    if (!$glob.HTTP_CRYPTO) console.warn('解密结果为空', json);
    return {};
  }
  debugger;
  let obj;
  try {
    obj = JSON.parse(json);
  } catch (e) {
    if (!$glob.HTTP_CRYPTO) console.warn('解析JSON出错，非JSON标准格式', e);
    return {};
  }
  return obj.aesData || {};
}

const key = $crypto.enc.Utf8.parse($glob.AES_KEY);
const iv = $crypto.enc.Utf8.parse($glob.AES_IV);

// AES 加密
function encryptAes(word) {
  let encrypted = $crypto.AES.encrypt(word, key, {
    iv: iv,
    mode: $crypto.mode.CBC,
    padding: $crypto.pad.Pkcs7
  });
  const hex = encrypted.ciphertext.toString().toUpperCase();
  const encryptedHexStr = $crypto.enc.Hex.parse(hex);
  return $crypto.enc.Base64.stringify(encryptedHexStr);
}

// 解密方法
function decryptAes(word) {
  const decrypt = $crypto.AES.decrypt(word, key, {
    iv: iv,
    mode: $crypto.mode.CBC,
    padding: $crypto.pad.Pkcs7
  });
  const decryptedStr = decrypt.toString($crypto.enc.Utf8);
  return decryptedStr.toString();
}



//加密方法
function encryptAes1(word){
  let srcs = Cry$cryptoptoJS.enc.Utf8.parse(word);
  let encrypted = $crypto.AES.encrypt(srcs, key, { iv: iv, mode: $crypto.mode.CBC, padding: $crypto.pad.Pkcs7 });
  return encrypted.ciphertext.toString().toUpperCase();
}
//解密方法
function Decrypt(word){
  let encryptedHexStr = $crypto.enc.Hex.parse(word);
  let srcs = $crypto.enc.Base64.stringify(encryptedHexStr);
  let decrypt = $crypto.AES.decrypt(srcs, key, { iv: iv, mode: $crypto.mode.CBC, padding: $crypto.pad.Pkcs7 });
  let decryptedStr = decrypt.toString($crypto.enc.Utf8);
  return decryptedStr.toString();
}



export default {
  encrypt,
  decrypt,
  Encode,
  Decode,
  MD5,
  encryptAes,
  decryptAes,
};
